<script setup>
import axios from "axios";
import { ref, reactive, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useShopcartStore } from "@/stores/shopcart";
import { ElMessage } from "element-plus";

const route = useRoute();
const router = useRouter();
const shopcartStore = useShopcartStore();

let subjectData = ref(null);
let categories = ref([]);
let booksByCategory = reactive({});
let loading = ref(false);

let props = defineProps(["index"]);

// 获取主题数据
const getTopicData = async () => {
  loading.value = true;
  try {
    const res = await axios.get("/api/booksSubject");
    console.log("booksSubject response:", res.data);

    if (res.data.code === 200) {
      // 找到当前选择的主题
      const currentSubject = res.data.data.find(
        (item) => item.sub_id === Number(props.index) + 1
      );

      if (currentSubject) {
        console.log("Found subject:", currentSubject);
        subjectData.value = currentSubject;

        // 获取该主题下的分类
        getCategoriesBySubject();
      } else {
        console.error("Subject not found, using default");
        subjectData.value = setDefaultSubject();
        categories.value = setDefaultCategories();
        loadDefaultBooks();
      }
    } else {
      console.error(
        "Failed to load subject data, using default",
        res.data.message
      );
      subjectData.value = setDefaultSubject();
      categories.value = setDefaultCategories();
      loadDefaultBooks();
    }
  } catch (err) {
    console.error("Error loading subject data, using default:", err);
    subjectData.value = setDefaultSubject();
    categories.value = setDefaultCategories();
    loadDefaultBooks();
  } finally {
    loading.value = false;
  }
};

// 获取主题下的分类
const getCategoriesBySubject = async () => {
  try {
    const res = await axios.get("/api/category");
    console.log("Category response:", res.data);

    if (res.data.code === 200) {
      // 过滤出当前主题的分类
      const filteredCategories = res.data.data.filter(
        (category) => category.sub_id === Number(props.index) + 1
      );

      if (filteredCategories.length > 0) {
        console.log("Found categories:", filteredCategories);
        categories.value = filteredCategories;

        // 获取每个分类下的书籍
        categories.value.forEach((category) => {
          getBooksByCategory(category.c_id);
        });
      } else {
        console.error("No categories found for this subject, using default");
        categories.value = setDefaultCategories();
        loadDefaultBooks();
      }
    } else {
      console.error(
        "Failed to load categories, using default:",
        res.data.message
      );
      categories.value = setDefaultCategories();
      loadDefaultBooks();
    }
  } catch (err) {
    console.error("Error loading categories, using default:", err);
    categories.value = setDefaultCategories();
    loadDefaultBooks();
  }
};

// 获取分类下的书籍
const getBooksByCategory = async (categoryId) => {
  try {
    console.log(`Fetching books for category ID: ${categoryId}`);
    const res = await axios.get(`/api/booksByCategory/${categoryId}`);
    console.log(`Response for category ${categoryId}:`, res.data);

    if (res.data.code === 200 && res.data.data && res.data.data.length > 0) {
      booksByCategory[categoryId] = res.data.data;
      console.log(
        `Books for category ${categoryId}:`,
        booksByCategory[categoryId]
      );
    } else {
      console.error(`No books found for category ${categoryId}, using default`);
      booksByCategory[categoryId] = getDefaultBooks(categoryId);
    }
  } catch (err) {
    console.error(
      `Error loading books for category ${categoryId}, using default:`,
      err
    );
    booksByCategory[categoryId] = getDefaultBooks(categoryId);
  }
};

// 加载所有默认书籍
const loadDefaultBooks = () => {
  categories.value.forEach((category) => {
    booksByCategory[category.c_id] = getDefaultBooks(category.c_id);
  });
};

// 监听路由参数变化
watch(
  () => props.index,
  () => {
    getTopicData();
  }
);

// 组件挂载时加载数据
onMounted(() => {
  getTopicData();
});

// 添加一个简单的错误处理函数
const handleError = (message) => {
  console.error(message);
  // 如果需要，可以在这里显示一个错误提示给用户
};

// 提供默认的分类数据，以防API调用失败
const setDefaultCategories = () => {
  if (props.index === "0") {
    // 拉美文学世界
    return [
      {
        c_id: 1,
        c_name: "经典文学作品",
        sub_id: 1,
        recom:
          "我们不会停止阅读，即使每本书总有读完的时候，如同我们不会停止生活，即使死亡必然来临。",
      },
      {
        c_id: 2,
        c_name: "诗歌与散文",
        sub_id: 1,
        recom: "我出生的那一天，上帝正好生病。",
      },
      {
        c_id: 3,
        c_name: "文学评论与研究",
        sub_id: 1,
        recom: "文学作品的一个重要功能就是记录和反映现实。",
      },
      {
        c_id: 4,
        c_name: "作家访谈与传记",
        sub_id: 1,
        recom: "我本想成为一名凶杀案侦探，而不是作家。",
      },
      {
        c_id: 5,
        c_name: "拉美文化概况",
        sub_id: 1,
        recom: "拉丁美洲的特性，拉丁美洲的文化",
      },
    ];
  } else if (props.index === "1") {
    // 女性主义的思与行
    return [
      {
        c_id: 6,
        c_name: "社科新知：她的发现",
        sub_id: 2,
        recom: "以笔为杆，慧眼如炬，深入剖析妇女面临的社会问题......",
      },
      {
        c_id: 7,
        c_name: "历史回顾：她的足迹",
        sub_id: 2,
        recom: "历史长河中，她们留下了灿烂的身影......",
      },
      {
        c_id: 8,
        c_name: "非虚构纪实：她的故事",
        sub_id: 2,
        recom: "如野草般坚韧，如太阳般明亮。",
      },
      {
        c_id: 9,
        c_name: "职场励志：无畏的她",
        sub_id: 2,
        recom: "脚踏实地、充满自信地生活和工作。",
      },
      {
        c_id: 10,
        c_name: "文学艺术：她的创作",
        sub_id: 2,
        recom: "女性既是书中的主角，又是创作者。",
      },
    ];
  } else if (props.index === "2") {
    // 她决定变成一棵树
    return [
      { c_id: 11, c_name: "她写她生活", sub_id: 3, recom: "我想抓住那道光" },
      {
        c_id: 12,
        c_name: "她写她幻想",
        sub_id: 3,
        recom: "他们的生活，不是属于人类的生活，而是出于动物本能般的生存。",
      },
      {
        c_id: 13,
        c_name: "他人与社会",
        sub_id: 3,
        recom: "工作能换来金钱，支撑怀抱的梦想，支付现实的关卡。",
      },
    ];
  } else if (props.index === "3") {
    // 书里
    return [
      {
        c_id: 14,
        c_name: "书店记忆",
        sub_id: 4,
        recom:
          "走访多家书店，记录书店的过去与现状、探讨书店的未来，以自己独特的视角和方式，将淘书以及与书发生的种种缘分和故事、阅读心得，结集为书。",
      },
    ];
  }
  return [];
};

// 提供默认的主题数据，以防API调用失败
const setDefaultSubject = () => {
  const subjects = [
    {
      sub_id: 1,
      sub_name: "不止魔幻：拉美文学世界",
      sub_img:
        "https://imgt.bookschina.com/2024/9/1c59c596-943e-474a-a7bd-ffca382ae61b.jpg",
      bgImg:
        "https://imgt.bookschina.com/2024/9/f20e4e4c-05aa-42b5-adfa-b0aac727926a.jpg",
      bgColor: "#f9d8be",
      titleColor: "#ba3119",
    },
    {
      sub_id: 2,
      sub_name: "当她们觉醒 女性主义的思与行",
      sub_img:
        "https://imgt.bookschina.com/2024/7/5431e172-ebb4-42d1-a385-d466e83192f6.jpg",
      bgImg:
        "https://imgt.bookschina.com/2024/7/229e0324-17c4-4f4b-ac8d-b8589ce33089.jpg",
      bgColor: "#ffc8be",
      titleColor: "#aa483e",
    },
    {
      sub_id: 3,
      sub_name: "她决定变成一棵树",
      sub_img:
        "https://imgt.bookschina.com/2024/10/4645d29d-c44d-45ff-b8d3-17a7b2dca2c0.jpg",
      bgImg:
        "https://imgt.bookschina.com/2024/10/9233e69d-9c70-48ab-bb6a-77066183a5e9.jpg",
      bgColor: "#fff1de",
      titleColor: "#db500b",
    },
    {
      sub_id: 4,
      sub_name: "书里",
      sub_img:
        "https://imgt.bookschina.com/2021/7/31c3b1ac-97ed-41d1-8ffc-0f05ed5eb445.jpg",
      bgImg:
        "https://imgt.bookschina.com/2021/7/ca403d39-1c9d-4775-b9a2-90037b226924.jpg",
      bgColor: "#c3f3f9",
      titleColor: "#2a315e",
    },
  ];

  return subjects[Number(props.index)];
};

// 提供默认的书籍数据，以防API调用失败
const getDefaultBooks = (categoryId) => {
  const allBooks = {
    // 拉美文学世界 - 经典文学作品
    1: [
      {
        b_id: 1,
        bookname: "米格尔在智利的地下行动",
        author: "加西亚.马尔克斯",
        publish: "南海出版公司",
        price: 49.0,
        img: "https://image12.bookschina.com/2019/20190722/1/s8134300.jpg",
      },
      {
        b_id: 3,
        bookname: "世界末日之战-企鹅经典",
        author: "(秘鲁)马里奥·巴尔加斯·略萨著;赵德",
        publish: "上海文艺出版社",
        price: 59.0,
        img: "https://image12.bookschina.com/2015/20150218/s6755809.jpg",
      },
      {
        b_id: 5,
        bookname: "百年孤独",
        author: "(哥伦)加西亚·马尔克斯",
        publish: "南海出版公司",
        price: 55.0,
        img: "https://image12.bookschina.com/2017/20170828/s7554065.jpg",
      },
    ],
    // 拉美文学世界 - 诗歌与散文
    2: [
      {
        b_id: 8,
        bookname: "群山自黄金",
        author: "[阿根廷] 莱奥波尔多·卢贡内斯 著，张礼骏 译",
        publish: "东方出版中心",
        price: 48.0,
        img: "https://image12.bookschina.com/2020/20200726/2/s8255002.jpg",
      },
      {
        b_id: 9,
        bookname: "写给星期五早上不听海的人:聂鲁达诗歌精选集",
        author: "[智利] 巴勃罗·聂鲁达 著，盛妍 等译",
        publish: "南海出版公司",
        price: 49.0,
        img: "https://image12.bookschina.com/2022/20220617/1/s8850328.jpg",
      },
    ],
    // 女性主义的思与行 - 社科新知
    6: [
      {
        b_id: 57,
        bookname: "看不见的女性",
        author: "（英）卡罗琳·克利亚多·佩雷斯",
        publish: "新星出版社",
        price: 69.0,
        img: "https://image31.bookschina.com/2022/zuo/8/s8900518.jpg",
      },
      {
        b_id: 58,
        bookname: "语言恶女:女性如何夺回语言",
        author: "[美]阿曼达·蒙特尔/著 李辛/译",
        publish: "北京联合出版公司",
        price: 62.0,
        img: "https://image12.bookschina.com/2024/20240607/12/s9341491.jpg",
      },
    ],
    // 书店记忆
    14: [
      {
        b_id: 33,
        bookname: "我在书店等你:阅在心里 读在途中",
        author: "朱晓健",
        publish: "金城出版社",
        price: 58.0,
        img: "https://image12.bookschina.com/2020/20200117/1/s8245655.jpg",
      },
      {
        b_id: 34,
        bookname: "海天译丛加缪书店",
        author: "[法]卡乌特·阿迪米",
        publish: "海天出版社",
        price: 42.0,
        img: "https://image12.bookschina.com/2019/20190302/2/s8015146.jpg",
      },
      {
        b_id: 35,
        bookname: "书店里的七种人",
        author: "(英)肖恩·白塞尔",
        publish: "北京联合出版公司",
        price: 49.8,
        img: "https://image31.bookschina.com/2021/zuo/10/s8654954.jpg",
      },
    ],
  };

  return allBooks[categoryId] || [];
};

// 添加到购物车
const addToCart = async (book) => {
  const result = await shopcartStore.addToCart(book.b_id, 1);
  console.log(result.success);

  if (result.success) {
    ElMessage.success("加入购物车成功");
  } else {
    ElMessage.error(result.message || "加入购物车失败");
  }
};

// 前往书籍详情页
const goToBookDetail = (bookId) => {
  router.push(`/booksDetails/${bookId}`);
};
</script>

<template>
  <div v-if="loading" class="loading-container">
    <el-skeleton :rows="10" animated />
  </div>

  <div v-else-if="subjectData">
    <div class="bodyFrame" :style="`background-color:${subjectData.bgColor}`">
      <!-- Banner区域 -->
      <div
        class="banner"
        :style="`background-image: url(${subjectData.bgImg});`"
      >
        <div class="inner">
          <img alt="" :src="subjectData.sub_img" />
        </div>
      </div>

      <!-- 遍历显示每个分类及其书籍 -->
      <div v-for="category in categories" :key="category.c_id">
        <div class="title">
          <h3
            :style="`background-color: ${subjectData.titleColor}; color: #ffffff; font-size: 24px`"
          >
            {{ category.c_name }}
          </h3>
        </div>

        <div class="line12">
          <div class="recom" id="divRecom">
            <h6>推荐语：</h6>
            <p title="category.recom">
              {{ category.recom }}
            </p>
          </div>

          <!-- 显示该分类下的书籍 -->
          <ul class="clearfix" id="partBooks">
            <li
              v-for="(book, index) in booksByCategory[category.c_id]"
              :key="index"
            >
              <div class="recomBox clearfix">
                <div class="Img bookLeft">
                  <a
                    @click.prevent="goToBookDetail(book.b_id)"
                    :title="book.bookname"
                  >
                    <img :src="book.img" class="Z120" :alt="book.bookname" />
                  </a>
                </div>
                <div class="text bookLeft">
                  <p class="name">
                    <a
                      @click.prevent="goToBookDetail(book.b_id)"
                      :title="book.bookname"
                    >
                      {{ book.bookname }}
                    </a>
                  </p>
                  <div class="auPu">
                    <p class="author">
                      作者：<b>{{ book.author }}</b>
                    </p>
                    <p class="publish">
                      出版社：<b>{{ book.publish }}</b>
                    </p>
                  </div>
                  <div class="actLabel"></div>
                  <div class="priceWrap">
                    <p class="np">
                      定价：<span>¥{{ book.price }}</span>
                    </p>
                  </div>
                  <p class="add">
                    <a
                      href="javascript:void(0);"
                      @click.prevent="addToCart(book)"
                      >加入购物车</a
                    >
                  </p>
                </div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <div v-else class="error-container">
    <p>未找到主题数据，请返回首页重试。</p>
    <el-button type="primary" @click="$router.push('/')">返回首页</el-button>
  </div>
</template>

<style scoped>
.bodyFrame {
  padding-bottom: 20px;
}
.banner {
  background-repeat: repeat;
  background-position: center top;
  height: 400px;
}
.banner .inner {
  width: 1000px;
  margin: 0 auto;
  position: relative;
}
img {
  border: 0;
}
.title {
  width: 1000px;
  margin: 0px auto 15px;
}
.title h2,
.title h3 {
  border-radius: 4px;
  height: 50px;
  color: #333;
  line-height: 50px;
  color: #fff;
  font-size: 26px;
  font-weight: normal;
  margin-top: 10px;
  text-align: center;
}
.line12 {
  padding: 20px 0px 0px;
  width: 1000px;
  margin: 0 auto;
  overflow: hidden;
  /* background: rgba(255, 255, 255, 0.4); */
  background-color: #f7f7f7;
  border-radius: 4px;
  position: relative;
  margin-bottom: 20px;
}
.line12 .recom {
  padding: 0px 20px;
}
.recom h6 {
  font-size: 16px;
  color: #666;
  /* color: #fff; */
  margin-bottom: 10px;
}
.line12 .recom h6 {
  text-align: left;
}
.recom p {
  font-size: 12px;
  line-height: 22px;
  margin-bottom: 15px;
  color: #666;
  /* color: #fff; */
  min-height: 20px;
  text-align: justify;
}
.line12 ul {
  padding-left: 20px;
}
.clearfix {
  zoom: 1;
  display: block;
}
ul li {
  list-style: none;
  margin: 0;
  padding: 0;
  line-height: 24px;
  color: #333333;
}
.line12 li {
  width: 470px;
  float: left;
  background: #fff;
  margin: 0px 20px 20px 0px;
  display: inline;
  /* background: rgba(255, 255, 255, 0.4); */
  background-color: #f7f7f7;
  border-radius: 4px;
  position: relative;
}
.recomBox {
  background-color: #fff;
  border-radius: 4px;
}
.line12 li .recomBox {
  padding: 15px 0px;
}
.Img {
  text-align: center;
  padding: 10px;
}
.line12 .Img {
  width: 170px;
  height: 150px;
}
.bookLeft {
  float: left;
}
.Img a {
  display: block;
}
ul li a {
  list-style: none;
  margin: 0;
  padding: 0;
  color: #333333;
  text-decoration: none;
}
.line12 li .Img img {
  height: 150px;
  max-width: 150px;
}

.text {
  width: 270px;
}
.name {
  height: 40px;
  overflow: hidden;
  margin-bottom: 10px;
}
.name a {
  font-size: 14px;
  color: #333;
}
.name a:hover {
  color: #e60000;
  text-decoration: underline;
}
.auPu {
  margin-bottom: 5px;
}
.auPu p {
  line-height: 20px;
  color: #999;
}
.priceWrap {
  height: 30px;
  line-height: 30px;
  margin-bottom: 10px;
}
.priceWrap .np {
  color: #666;
}
.priceWrap .np span {
  font-size: 16px;
  color: #e60000;
  font-weight: bold;
}
.add a {
  display: inline-block;
  width: 90px;
  height: 25px;
  line-height: 25px;
  background-color: #e60000;
  color: #fff;
  text-align: center;
  border-radius: 3px;
}
.add a:hover {
  background-color: #ff3333;
}

.loading-container,
.error-container {
  padding: 100px 0;
  text-align: center;
  width: 1000px;
  margin: 0 auto;
}

.error-container p {
  margin-bottom: 20px;
  font-size: 16px;
  color: #666;
}
</style>
